﻿using System.Collections.Generic;
using Engine;
using Engine.Objects.StaticObjects;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace EngineDrawer.Objects.StaticObjects
{
    public class StaticObjectDrawer : DrawableGameComponent
    {        
        public StaticObjectDrawer(Game game)
            : base(game)
        {
        }

        #region Properties
        
        public World World
        {
            get { return (World)Game.Services.GetService(typeof (World)); }
        }

        #endregion        

        #region Public Methods

        public override void Draw(GameTime gameTime)
        {
            GraphicsDevice.BlendState = BlendState.Opaque;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            if (World.StaticObjects != null)
            {
                foreach (var staticObject in World.StaticObjects)
                {
                    if(staticObject.Visible)
                        DrawObject(staticObject);
                }
            }
            base.Draw(gameTime);
        }

        #endregion  

        #region Private Methods

        private void DrawObject(StaticObject staticObject)
        {
            Matrix[] transforms = new Matrix[staticObject.Model.Bones.Count];
            staticObject.Model.CopyAbsoluteBoneTransformsTo(transforms);

            foreach (ModelMesh mesh in staticObject.Model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World = transforms[mesh.ParentBone.Index]*staticObject.WorldMatrix;
                    effect.View = World.ViewMatrix;
                    effect.Projection = World.ProjMatrix;
                }
                mesh.Draw();
            }
        }

        #endregion
    }
}
